package io.github.cisumer.wcfbin4j.nodes.texts;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.TimeZone;

import org.apache.commons.lang3.time.DateFormatUtils;

import io.github.cisumer.wcfbin4j.nodes.TextRecord;
import io.github.cisumer.wcfbin4j.util.ByteArrayUtil;

/**
 * 日期<br/>
 * [2][62] [tz][date] 00 1B 45 BA BD A9 D9 08 >> 2021-11-17 19:30:58
 * @author github.com/cisumer
 *
 */
public class DateTimeText extends TextRecord<Date> {
	public final static long TIME_LINE = 62135596800000l;// 1-1-1 0:0:0 到1970-1-1 0:0:0 的毫秒数    
	public final static long BASE_TIME_UNIT = 10 * 1000;//100纳秒为基数
	
	private int tz= 0;

	@Override
	public int getType() {
		return 0x96;
	}

	@Override
	public void parse(InputStream is) throws IOException {
		byte[] bs = new byte[8];
		is.read(bs);
		ByteArrayUtil.reverse(bs);
		ByteBuffer bb = ByteBuffer.wrap(bs);
		long l = bb.getLong();
		tz = (int)(l >> 62) & 3;
		value = new Date((l & 0x3FFFFFFFFFFFFFFFL)/BASE_TIME_UNIT - TIME_LINE);//换算成毫秒
	}

	@Override
	public void renderContent(OutputStream os) throws Exception {
		ByteBuffer bb = ByteBuffer.allocate(8);
		long times= (long)((tz & 3) << 62) |
				    ((value.getTime() + TIME_LINE)*BASE_TIME_UNIT & 0x3FFFFFFFFFFFFFFFL);//先折算到100纳秒
		bb.putLong(times);
		byte[] bs = bb.array();
		ByteArrayUtil.reverse(bs);
		os.write(bs);
	}
	public String toXML() {
		String format="yyyy-MM-dd HH:mm:ss";
		TimeZone timezone=TimeZone.getTimeZone("GMT");
		if(tz>0)
			timezone=TimeZone.getDefault();
		return DateFormatUtils.format(value, format,timezone);
	}
	public DateTimeText setTimeZone(byte timezone){
		this.tz=(timezone>>2) & 3;
		return this;
	}
}
